package pers.crayon.baseprogram.config;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 内嵌tomcat的默认配置存在于
 * ServerProperties类存在内部静态类 Tomcat 内部类中有tomcat 各参数
 * 也可以通过配置配置文件来定义tomcat，因为tomcat对象创建时也会读取配置文件对应项
 * <p>
 * 自定义config叫 Customizer 比较好
 * 详细配置需要后续研究tomcat组件
 *
 * @author wangzg13
 * @since 2022/9/8
 */
public class TomcatConfig implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Value("${server.additionalPorts}")
    private String additionalPorts;


    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        Connector[] additionalTomcatConnectors = getAdditionalConnectors();
        factory.addAdditionalTomcatConnectors(additionalTomcatConnectors);
    }

    /**
     * 多端口监听
     *
     * @return
     */
    private Connector[] getAdditionalConnectors() {
        if (StringUtils.hasLength(additionalPorts)) {
            return null;
        }
        String[] ports = additionalPorts.split(",");
        List<Connector> connectors = new ArrayList<>();
        for (String port : ports) {
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setPort(Integer.parseInt(port));
            connector.setScheme("http");
            connectors.add(connector);
        }
        // list 转数组
        return connectors.toArray(new Connector[]{});
    }
}
